<template>
  <view class="order-closure-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="订单关闭列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <view class="search-bar">
            <view class="search-bar-item" @click="showPicker1 = true">
              <text class="title">是否本人</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <up-picker :show="showPicker1" :columns="columns1" :closeOnClickOverlay="true"
              @confirm="handleOwnerConfirm" @cancel="showPicker1 = false" @close="showPicker1 = false"></up-picker>
          </view>

          <up-search 
            v-model="searchKeyword" 
            :clearabled="true" 
            :showAction="true" 
            placeholder="请输入关键字查询"
            @search="handleSearch"
            @clear="handleClear">
          </up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="order-closure-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              场地名称：<text class="number">{{ item.veName || '未知场地' }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  状态
                </text>
                <view class="value">
                  <view class="item-tag">
                    <up-tag 
                      :text="getStatusText(item.status)" 
                      :type="getStatusType(item.status)">
                    </up-tag>
                  </view>
                </view>
              </view>
              <view class="item">
                <text class="label">
                  审核ID：
                </text>
                <text class="value">
                  {{ item.bizCode || '无' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  计费规则名称：
                </text>
                <text class="value">
                  {{ item.name || '无' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  提交人：
                </text>
                <text class="value">
                  {{ item.operateName || '无' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  创建时间：
                </text>
                <text class="value">
                  {{ formatTime(item.createTime) }}
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="checkbox-box">
              </view>
              <view class="operate">
                <up-button type="primary" text="申诉记录" plain class="custom-style" @click="handleEdit(item)"></up-button>
                <up-button type="primary" text="通过申诉" class="custom-style" @click="handlePass(item)"></up-button>
                <up-button type="error" text="拒绝申诉" class="custom-style" @click="handleRefuse(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <OrderAppealModal v-model:show="show" :type="type" :row-data="editingData" />

  <!-- 通过审核弹窗 -->
  <up-modal 
    :show="showApproveModal" 
    title="审核通过" 
    :showCancelButton="true" 
    confirmText="确认通过"
    @confirm="handleApproveConfirm" 
    @cancel="handleApproveCancel"
  >
    <view class="modal-content">
      <view class="user-info">
        <text class="info-text">确定要通过该订单关闭申请吗？</text>
      </view>
      <view class="form-item">
        <text class="label">审核备注：</text>
        <up-textarea 
          v-model="approveForm.remark" 
          placeholder="请输入审核备注（可选）" 
          :maxlength="200" 
          count
          showWordLimit
        ></up-textarea>
      </view>
    </view>
  </up-modal>

  <!-- 拒绝审核弹窗 -->
  <up-modal 
    :show="showRejectModal" 
    title="审核驳回" 
    :showCancelButton="true" 
    confirmText="确认驳回"
    @confirm="handleRejectConfirm" 
    @cancel="handleRejectCancel"
  >
    <view class="modal-content">
      <view class="user-info">
        <text class="info-text">确定要驳回该订单关闭申请吗？</text>
      </view>
      <view class="form-item">
        <text class="label">驳回原因：<text class="required">*</text></text>
        <up-textarea 
          v-model="rejectForm.remark" 
          placeholder="请输入驳回原因" 
          :maxlength="200" 
          count
          showWordLimit
        ></up-textarea>
      </view>
    </view>
  </up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getOrderCloseAuditList, authorOrderCloseAudit } from '@/api';
import OrderAppealModal from './components/OrderAppealModal.vue'

const { bool: show, setTrue: openModal } = useBoolean();
const type = ref('add')
const editingData = ref({})

// 审核弹窗相关
const showApproveModal = ref(false)
const showRejectModal = ref(false)
const currentItem = ref(null)
const approveForm = ref({
  remark: ''
})
const rejectForm = ref({
  remark: ''
})

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '待审核' },
  { name: '已审核' },
];
const currentTab = ref(0);
const showPicker1 = ref(false);
const searchKeyword = ref('');

const columns1 = reactive([
  ['全部', '否', '是'],
]);
// 是否本人选项索引
const ownerIndex = ref(0);
// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

const handleAdd = () => {
  type.value = 'add'
  openModal()
}

const handleEdit = (item: any) => {
  type.value = 'edit'
  editingData.value = {
    carNumber: '粤XZ5168',
    modifyTime: Date.now(),
  }
  openModal()
}

const handlePass = (item: any) => {
  currentItem.value = item
  approveForm.value.remark = ''
  showApproveModal.value = true
}

const handleApproveConfirm = () => {
  // 确认通过审核
  showApproveModal.value = false

  // 调用审核通过接口
  uni.showLoading({ title: '处理中...' })

  authorOrderCloseAudit({
    bizCode: currentItem.value.bizCode,
    author: 0, // 0表示通过
    dealRemark: approveForm.value.remark || '审核通过'
  }).then(() => {
    uni.hideLoading()
    uni.showToast({
      title: '审核已通过',
      icon: 'success'
    })
    // 刷新列表
    if (paging.value) {
      paging.value.reload()
    }
  }).catch(err => {
    uni.hideLoading()
    uni.showToast({
      title: err.message || '操作失败',
      icon: 'none'
    })
  })
}

const handleApproveCancel = () => {
  showApproveModal.value = false
}

const handleRefuse = (item: any) => {
  currentItem.value = item
  rejectForm.value.remark = ''
  showRejectModal.value = true
}

const handleRejectConfirm = () => {
  // 验证是否填写了拒绝原因
  if (!rejectForm.value.remark) {
    uni.showToast({
      title: '请填写拒绝原因',
      icon: 'none'
    })
    return
  }

  // 确认拒绝审核
  showRejectModal.value = false

  // 调用拒绝审核接口
  uni.showLoading({ title: '处理中...' })

  authorOrderCloseAudit({
    bizCode: currentItem.value.bizCode,
    author: 1, // 1表示拒绝
    dealRemark: rejectForm.value.remark
  }).then(() => {
    uni.hideLoading()
    uni.showToast({
      title: '已拒绝审核',
      icon: 'success'
    })
    // 刷新列表
    if (paging.value) {
      paging.value.reload()
    }
  }).catch(err => {
    uni.hideLoading()
    uni.showToast({
      title: err.message || '操作失败',
      icon: 'none'
    })
  })
}

const handleRejectCancel = () => {
  showRejectModal.value = false
}

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}


// 获取车辆列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    const result: any = await getOrderCloseAuditList({ 
      ...params, 
      isAuthor: currentTab.value === 0 ? -1 : (currentTab.value === 1 ? 0 : 1),
      isOwn: ownerIndex.value === 0 ? undefined : (ownerIndex.value === 1 ? 0 : 1),
      keyword: searchKeyword.value || undefined
    })
    const data = result.data
    paging.value.complete(data.records || [])
  } catch (error) {
    paging.value.complete(false)
  }
}

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchKeyword.value = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理是否本人选项确认
const handleOwnerConfirm = (e) => {
  ownerIndex.value = e.indexs[0];
  showPicker1.value = false;
  // 刷新列表
  if (paging.value) {
    paging.value.reload();
  }
};

// 查看详情
const handleView = (row: any) => {
  // 跳转到详情页逻辑
  console.log('查看详情:', row);
};

// 审核操作
const handleVerify = (row: any) => {
  // 跳转到审核页逻辑
  console.log('审核操作:', row);
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '待审核'
    case 2:
      return '审核通过'
    case 3:
      return '审核驳回'
    default:
      return '未知状态'
  }
}

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'error'
    default:
      return 'info'
  }
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '无'
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.order-closure-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  &-item {
    display: flex;
    flex: 1;
    align-items: center;
    text-align: center;

    .item-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

/* 列表统计 */
.list-statistics {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.list-statistics .item {
  flex: 1 1 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.list-statistics .label {
  font-size: 14px;
  color: #666;
}

.list-statistics .value {
  font-size: 18px;
  font-weight: bold;
  color: #e9710f;
}

/* 弹窗样式 */
.modal-content {
  padding: 20px;
}

.user-info {
  margin-bottom: 15px;
}

.info-text {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.form-item {
  margin-bottom: 10px;
}

.label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #333;
}

.required {
  color: #ff4d4f;
  margin-left: 2px;
}
</style>